import {getToken, setToken, removeToken} from '@/utils/auth'
import {login, getUserInfo, getCurrencyInfo, logout} from "@/api/login";
import {getPhones, savePhone} from "../../utils/savePhone";

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    phone: '',
    userInfo:{
      user: {},
      user_money: {}
    },
    currencyInfo: []
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      console.log(state)
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PHONE: (state, roles) => {
      state.phone = roles
    },
    SET_USERINFO: (state,userinfo) => {
      state.userInfo=userinfo;
    },
    SET_CURRENCY_INFO: (state,currencyInfo) => {
      state.currencyInfo=currencyInfo;
    }
  },
  actions: {
// 登录
    Login({commit}, userInfo) {
      let {type} = userInfo;
      let info = {...userInfo};
      delete info['type'];
      return new Promise((resolve, reject) => {
        login(info, type).then(response => {
          console.log(response);
          const data = response;
          setToken(data.token);
          commit('SET_TOKEN', data.token)
          resolve(data)
        }).catch(error => {
          // console.log(error + "11111");
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({commit, state, dispatch}) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(response => {
          // console.log("获取用户信息中....");
          // console.log(response);
          const userinfo = response.data
          commit('SET_USERINFO', userinfo);
          resolve(userinfo)
        }).catch(error => {
          console.log("error=>获取用户信息失败")
          reject(error)
        })
      })
    },

    GetCurrencyInfo ({commit, state, dispatch}, data) {
      return new Promise((resolve, reject) => {
        getCurrencyInfo(data).then(response => {
          // console.log("获取用户信息中....");
          // console.log(response);
          const currencyInfo = response.data
          commit('SET_CURRENCY_INFO', currencyInfo);
          resolve(currencyInfo)
        }).catch(error => {
          console.log("error=>获取用户信息失败")
          reject(error)
        })
      })
    },
    //保存手机号
    saveHistoryPhone({commit, state}, phone) {
      savePhone(phone);
    },

    // 登出
    LogOut({commit, state, dispatch}) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          commit('SET_PHONE', '');
          commit('SET_NAME', '');
          commit('SET_AVATAR', '');
          commit('SET_USERINFO', {
            user: {},
            user_money: {}
          });
          removeToken();
          const phones = getPhones();
          localStorage.clear();
          savePhone(phones);
          resolve();
        })
      })
    }
  }
};

export default user;
